<template>
  <div class="img">
    <a-upload
      name="images"
      :class="[!imageMultiple?'img-upload':'',(!imageMultiple && picUrl)?'image-upload-single-over':'']"
      list-type="picture-card"
      :multiple="imageMultiple"
      :action="uploadAction"
      :headers="headers"
      :fileList="fileList"
      :before-upload="beforeUpload"
      :disabled="disabled"
      @preview="handlePreview"
      @change="handleChange">
      <div>
        <div class="iconp">
          <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
          <div class="ant-upload-text">{{ text }}</div>
        </div>
      </div>
      <a-modal
          :visible="previewVisible"
          :footer="null"
          @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-upload>
  </div>
</template>

<script>
import utils from "@/utils/utils";
import {deleteAction} from "@api/manage";

export default {
  name: "ImageUpload",
  props: {
    text:{
      type:String,
      required:false,
      default:"上传"
    },
    value:{
      type:[String,Array],
      required:false
    },
    disabled:{
      type:Boolean,
      required:false,
      default: false
    },
    imageMultiple:{
      type:Boolean,
      required:false,
      default: false
    },
    number:{
      type:Number,
      required:false,
      default:0
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data(){
    return {
      uploadAction:window._CONFIG['domianURL']+"/image/upload",
      deleteAction:"/image/delete",
      uploadLoading:false,
      picUrl:false,
      headers:{},
      fileList: [],
      previewImage:"",
      previewVisible: false,
    }
  },
  watch: {
    value: {
      handler(newVal,oldVal){
        console.info("newVal",newVal)
        if(newVal instanceof Array){
          this.initFileList(newVal.join(","));
        } else {
          this.initFileList(newVal);
        }

        if(!newVal || newVal.length===0){
          this.picUrl = false;
        }
      },
      immediate: true
    }
  },
  methods: {
    initFileList(filesStr){
      console.info("filesStr",filesStr)
      if(!filesStr || filesStr.length === 0){
        this.fileList = [];
        return false;
      }
      this.picUrl = true;
      let filesArr = filesStr.split(",");
      this.fileList = filesArr.map((fileUrl) => {
        return {
          uid: utils.getFileName(fileUrl),
          name: utils.getFileName(fileUrl),
          url: fileUrl,
          status: "done",
          response: {
            status: "history",
            message: "图片回显"
          }
        }
      });
    },

    beforeUpload: function(file){
      console.info("beforeUpload",file);
      let fileType = file.type;
      if(fileType.indexOf('image')<0){
        this.$message.warning('请上传图片');
        return false;
      }
    },

    handleChange(info) {
      console.info("handleChange",info);
      this.picUrl = false;
      let fileList = info.fileList
      //update-begin-author:wangshuai date:20201022 for:LOWCOD-969 判断number是否大于0和是否多选，返回选定的元素。
      if(this.number>0 && this.isMultiple){
        fileList = fileList.slice(-this.number);
      }
      //update-end-author:wangshuai date:20201022 for:LOWCOD-969 判断number是否大于0和是否多选，返回选定的元素。
      if(info.file.status==='done'){
        if(info.file.response.success){
          this.picUrl = true;
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.result[0].fileUrl;
            }
            return file;
          });
        }
        this.handlePathChange();
      }else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`);
      }else if(info.file.status === 'removed'){
        deleteAction(this.deleteAction,{fileName:info.file.name}).then((res)=>{
          if(res.success){
            this.handlePathChange();
          }else {
            info.file.status = 'done';
            fileList.push(info.file);
            this.$message.error(`${info.file.name}`+res.message);
          }
        });
      }
      this.fileList = fileList
    },
    // 预览
    handlePreview (file) {
      console.info("handlePreview",file)
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handlePathChange(){
      console.info("handlePathChange")
      let uploadFiles = this.fileList
      let path = ''
      if(!uploadFiles || uploadFiles.length==0){
        path = ''
      }
      let arr = [];
      if(!this.isMultiple && uploadFiles.length>0){
        arr.push(uploadFiles[uploadFiles.length-1].response.result[0].fileUrl)
      }else{
        for(let a=0;a<uploadFiles.length;a++){
          if(uploadFiles[a].status === 'done' ) {
            arr.push(uploadFiles[a].response.result[0].fileUrl)
          }else{
            return;
          }
        }
      }
      if(arr.length>0){
        path = arr.join(",")
      }
      this.$emit('change', path);
    },
    handleCancel() {
      this.close();
      this.previewVisible = false;
    },
    close () {

    },
  }
}
</script>

<style scoped>
/deep/ .img-upload .iconp {
  padding:20px;
}
/deep/ .image-upload-single-over .ant-upload-select {
  display: none
}
</style>